from threading import Timer

class ContinuousDbFunction(object):
    def __init__(self, db, step, function):
        self._db = db
        self._step=step
        self._function = function
        self._timer=Timer(self._step, self.start)

    def _exec(self):
        self.fun()
        self.start()

    def fun(self):
        self._function(self._db)

    def start(self):
        self._timer=Timer(self._step, self._exec)
        self._timer.start()

    def stop(self):
        self._timer.cancel()


class ContinuousPrintDbStats(ContinuousDbFunction):
    def __init__(self, db, step):
        ContinuousDbFunction.__init__(self, db, step, lambda db: db.printStats())

class ContinuousFlushDb(ContinuousDbFunction):
    def __init__(self, db, step):
        ContinuousDbFunction.__init__(self, db, step, lambda db: db.flush())

class ContinuousOptimizeDb(ContinuousDbFunction):
    def __init__(self, db, step):
        ContinuousDbFunction.__init__(self, db, step, lambda db: db.optimize())
